package com.zyw.mvc.exception.handler;

import com.alibaba.fastjson.JSON;
import com.zyw.mvc.exception.InvalidParameterException;
import com.zyw.mvc.exception.utils.ExceptionUtils;
import com.zyw.mvc.support.WrappedResult;

/**
 * @author huoli_zhangyw
 * @ClassName InvalidParameterExceptionHandler
 * @Description 参数异常处理器
 * @date 16/9/9 15:24
 */
public class InvalidParameterExceptionHandler extends RestExceptionHandler {

    public InvalidParameterExceptionHandler(boolean fullStack) {
        super(fullStack);
    }

    @Override
    protected boolean support(Exception e) {
        return InvalidParameterException.class.isAssignableFrom(e.getClass());
    }

    @Override
    protected WrappedResult handleInvoke(Exception e) {

        InvalidParameterException exception = (InvalidParameterException) e;

        if (exception.getErrorMessage() != null) {
            logger.warn(ExceptionUtils.getFullStackTrace(e));
            return WrappedResult.handleExceptionWrappedResult(exception.getCode(), JSON.toJSONString(exception.getErrorMessage()), null);
        }

        String exMessage = exception.getMessage();
        if (exMessage == null || "".equals(exMessage)) {
            logger.error(ExceptionUtils.getFullStackTrace(e));
            return WrappedResult.handleExceptionWrappedResult("服务端异常！");
        }

        logger.warn(ExceptionUtils.getFullStackTrace(e));

        if (isFullStack()) {
            return WrappedResult.handleExceptionWrappedResult(exception.getCode(), ExceptionUtils.getFullStackTrace(e), null);
        } else {
            return WrappedResult.handleExceptionWrappedResult(exception.getCode(), exMessage, null);
        }
    }
}
